# -*- coding:utf-8 -*-
# import json

from pymongo import MongoClient
from redis import Redis

client = MongoClient('127.0.0.1', 27017)
db = client['poems']


class PoemsDB:
    client = MongoClient('127.0.0.1', 27017)
    db = client['poems']
    collection = db['poem_collection']

    def insert(self, d):
        
        # d = dict(title=title, author=author, content=content)
        if self.collection.insert(d):
            return True
        else:
            return False

    def all(self):
        result = list(self.collection.find())
        for i in range(len(result)):
            one_result = dict(result[i])
            one_result.pop('_id')
            one_result['content'] = '\n'.join(one_result['content'])
            print(one_result)
            result[i] = one_result
        return result

    def delete(self, title):
        count = self.collection.delete_one({'title': title}).deleted_count
        if count:
            return True
        else:
            return False

    def search(self, title):
        result = self.collection.find_one({'title': title})
        result.pop('_id')
        return result


class DescDB:
    def __init__(self):
        client = MongoClient('127.0.0.1', 27017)
        db = client['poems']
        self.collection = db['desc']
        # print(self.collection)
    def change(self, username, data: dict):
        condition = {'username': username}
        find_result = self.collection.find(condition)
        self.collection.update(condition, data)

    def insert(self, username, data: dict):
        data.update({'username': username})
        if self.collection.find_one({'username': username}):
            self.change(username, data)
        else:
            self.collection.insert(data)


    def find(self, username):
        condition = dict(username=username)
        result = self.collection.find_one(condition)
        if not result:
            return result
        else:
            result = dict(result)
            result.pop('_id')
            return result


class UserDB:
    def __init__(self):
        self.connection = Redis('127.0.0.1', 6379, password='123456')
        # super().__init__

    def add(self, username, password):
        self.connection.hset('POEM_USER', username, password)

    def search(self, username):
        return self.connection.hget('POEM_USER', username)



